<template>
	<view class="user-page-container">
		<!-- 背景元素 -->
		<view class="page-background">
			<image src="/static/campus-ill.png" mode="widthFix" class="bg-image"></image>
		</view>

		<!-- 顶部个人信息区域 -->
		<view class="header-section">
			<template v-if="isLoggedIn">
				<view class="user-card">
					<view class="user-card-avatar" @click="goedituserinfo">
						<image class="avatar" :src="userInfo.avatar_file && userInfo.avatar_file.url ? userInfo.avatar_file.url : '/static/default-avatar.png'" mode="aspectFill"></image>
					</view>
					<view class="user-card-info">
						<view class="user-name-line">
							<text class="user-name">{{ userInfo.username || userInfo.nickname || '未设置昵称' }}</text>
							<uni-icons @click="goedituserinfo" type="compose" size="18" color="#000000" class="edit-icon" />
						</view>
						<view class="user-meta" @click="gocreditdetails">
							<text>信用等级: {{ userInfo.creditLevel || 'A级' }}</text>
						</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="not-login-container">
					<image class="default-avatar" src="/static/default-avatar.png" mode="aspectFill"></image>
					<view class="login-btn" @click="goToLogin">
						<text>去登录</text>
					</view>
				</view>
			</template>
			
		</view>

		<!-- 主要内容区域 -->
		<view class="content-wrapper">
			<!-- 新增功能导航区 -->
			<view class="card-section nav-section" v-if="isLoggedIn">
				<view class="nav-item cursor-pointer" @click="goToPoints">
					<uni-icons type="medal" size="26" color="#E6A23C"></uni-icons>
					<text class="nav-text">我的积分</text>
				</view>
				<view class="nav-item cursor-pointer" @click="goToWallet">
					<uni-icons type="wallet" size="26" color="#409EFF"></uni-icons>
					<text class="nav-text">我的钱包</text>
				</view>
			</view>

			<!-- 数据统计 -->
			<view class="stats-group">
				<!-- 任务数据 -->
				<view class="card-section data-card">
					<view class="card-header">
						<text class="card-title">任务数据</text>
					</view>
					<view class="data-grid">
						<view 
							class="data-item cursor-pointer" 
							v-for="(item, index) in taskData" 
							:key="index"
							@click="goToUserTask(item.type)"
						>
							<text class="data-value">{{ item.value }}</text>
							<text class="data-label">{{ item.label }}</text>
						</view>
					</view>
				</view>

				<!-- 圈子贡献 -->
				<view class="card-section data-card" @click="goToUserQuanzi">
					<view class="card-header">
						<text class="card-title">圈子贡献</text>
						<uni-icons type="right" size="14" color="#C0C4CC"></uni-icons>
					</view>
					<view class="data-grid">
						<view class="data-item" v-for="(item, index) in circleData" :key="index">
							<text class="data-value">{{ item.value }}</text>
							<text class="data-label">{{ item.label }}</text>
						</view>
					</view>
				</view>
				
				<!-- 活动数据 -->
				<view class="card-section data-card" @click="goToUserActivity">
					<view class="card-header">
						<text class="card-title">活动中心</text>
						<uni-icons type="right" size="14" color="#C0C4CC"></uni-icons>
					</view>
					<view class="data-grid">
						<view class="data-item" v-for="(item, index) in activityData" :key="index">
							<text class="data-value">{{ item.value }}</text>
							<text class="data-label">{{ item.label }}</text>
						</view>
					</view>
				</view>

				<!-- 登录蒙版 -->
				<view v-if="!isLoggedIn" class="login-mask" @click="goToLogin">
					<!-- <text class="mask-text">请先登录后查看</text> -->
				</view>
			</view>

			<!-- 在用户中心页面添加签到按钮和相关方法 -->
			<!-- 在模板中添加签到按钮 -->
			<view class="sign-section" v-if="isLoggedIn">
				<button class="sign-btn" @click="dailySign" :disabled="isSigning">
					<uni-icons type="calendar" size="20" color="#409EFF"></uni-icons>
					<text>{{ isSigning ? '签到中...' : '每日签到' }}</text>
				</button>
			</view>
		</view>

		<!-- 浮动客服按钮 -->
		<view class="floating-service-btn" @click="contactService">
			<uni-icons type="headphones" size="22" color="#FFFFFF"></uni-icons>
		</view>

		<customTabBar />
	</view>
</template>

<script>
import customTabBar from '@/components/CustomTabBar.vue';
export default {
	components:{
		customTabBar
	},
	data() {
		return {
			// 任务数据（每项增加type字段用于跳转）
			taskData: [
				{ label: '发布任务', value: '...', type: 'published' },
				{ label: '进行中任务', value: '...', type: 'processing' },
				{ label: '完成任务', value: '...', type: 'completed' }
			],

			// 圈子贡献
			circleData: [
				{ label: '发帖数', value: '...' },
				{ label: '评论数', value: '...' },
				{ label: '获赞数', value: '...' },
				{ label: '我的点赞', value: '...' }
			],
			
			// 活动数据
			activityData: [
				{ label: '发布活动', value: '...' },
				{ label: '参与活动', value: '...' }
			],

			// 登录状态相关
			isLoggedIn: false,
			userInfo: {},
			isSigning: false
		}
	},

	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const token = uni.getStorageSync('uni_id_token')
			this.isLoggedIn = !!token
		},

		// 跳转到登录页面
		goToLogin() {
			uni.navigateTo({
				url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
			})
		},

		// 跳转到个人信息编辑页面
		goedituserinfo() {
			uni.navigateTo({
				url: "/uni_modules/uni-id-pages/pages/userinfo/userinfo"
			})
		},

		// 跳转到任务中心页面
		goToUserTask(type) {
			uni.navigateTo({
				url: `/pages/user/user-task/user-task?type=${type}`
			})
		},

		// 跳转到积分详情页面
		gopointsdetails() {
			uni.navigateTo({
				url: '/pages/user/user-pointsdetails/user-pointsdetails'
			})
		},

		// 跳转到信用等级页面
		gocreditdetails() {
			uni.navigateTo({
				url: "/pages/user/user-creditdetails/user-creditdetails"
			})
		},

		// 跳转到圈子贡献页面
		goToUserQuanzi() {
			if (!this.isLoggedIn) return; // 蒙版已覆盖，此处增加一层防护
			uni.navigateTo({
				url: '/pages/user/user-quanzi/user-quanzi'
			})
		},

		goToUserActivity() {
			if (!this.isLoggedIn) {
				// 蒙版已覆盖，此处为额外防护
				this.goToLogin();
				return;
			}
			uni.navigateTo({
				url: '/pages/user/user-activity/user-activity'
			});
		},

		// 获取所有用户统计数据
		async getAllUserStats() {
			console.log('开始获取用户统计数据...');
			if (!this.userInfo || !this.userInfo._id) {
				console.log('获取用户统计数据中止：无用户信息。');
				return;
			}

			try {
				const res = await uniCloud.callFunction({
					name: 'getUserStats'
				});

				if (res.result.code === 200) {
					const data = res.result.data;
					
					// 更新任务数据
					this.taskData = data.taskData.map(item => ({
						...item,
						value: item.value.toString() // 确保显示为字符串
					}));

					// 更新圈子数据
					this.circleData = data.circleData.map(item => ({
						...item,
						value: item.value.toString()
					}));

					// 更新活动数据
					this.activityData = data.activityData.map(item => ({
						...item,
						value: item.value.toString()
					}));

					// 更新积分
					this.userInfo.score = data.totalScore;

					console.log('用户统计数据获取成功:', data);
				} else {
					console.error('获取用户统计数据失败:', res.result.msg);
					this.setDefaultData();
				}
			} catch (error) {
				console.error('获取用户统计数据异常:', error);
				this.setDefaultData();
			}
		},

		// 设置默认数据
		setDefaultData() {
			this.taskData = [
				{ label: '发布任务', value: '0', type: 'published' },
				{ label: '进行中任务', value: '0', type: 'processing' },
				{ label: '完成任务', value: '0', type: 'completed' }
			];

			this.circleData = [
				{ label: '发帖数', value: '0' },
				{ label: '评论数', value: '0' },
				{ label: '获赞数', value: '0' },
				{ label: '我的点赞', value: '0' }
			];

			this.activityData = [
				{ label: '发布活动', value: '0' },
				{ label: '参与活动', value: '0' }
			];
		},

		// 获取用户信息
		getUserInfo() {
			const info = uni.getStorageSync('uni-id-pages-userInfo')
			this.userInfo = info && info._id ? {
				...info,
				score: 0, // 初始化为0，等待计算
				creditLevel: info.creditLevel || 'A级'
			} : {}
			// 如果用户已登录，获取积分明细
			if (this.isLoggedIn && this.userInfo && this.userInfo._id) {
				this.getUserScore();
				this.getAllUserStats(); // 使用新的方法获取所有统计数据
			}
		},

		// 获取用户积分明细并计算总积分
		async getUserScore() {
			try {
				const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
				if (!userInfo || !userInfo._id) {
					this.userInfo.score = 0
					return
				}
				
				// 调用积分管理云函数获取积分记录
				const res = await uniCloud.callFunction({
					name: 'scoreManager',
					data: {
						action: 'get_records',
						userId: userInfo._id
					}
				})
				
				if (res.result.code === 200) {
					const data = res.result.data
					this.userInfo.score = data.totalScore || 0
					
					// 更新本地存储的用户信息
					const storedUserInfo = uni.getStorageSync('uni-id-pages-userInfo')
					if (storedUserInfo) {
						storedUserInfo.score = this.userInfo.score
						uni.setStorageSync('uni-id-pages-userInfo', storedUserInfo)
					}
				} else {
					this.userInfo.score = 0
				}
			} catch (error) {
				console.error('获取用户积分失败:', error)
				this.userInfo.score = 0
			}
		},

		goIndex() {
			uni.navigateTo({ url: '/pages/index/index' })
		},
		gocircle() {
			uni.navigateTo({ url: '/pages/circle/circle' })
		},
		gomessage() {
			uni.navigateTo({ url: '/pages/message/MessageCenter/MessageCenter' })
		},
		goToPoints() {
			uni.navigateTo({ url: '/pages/user/user-pointsdetails/user-pointsdetails' })
		},
		goToWallet() {
			uni.navigateTo({ url: '/pages/user/Wallet/Wallet' })
		},

		// 在用户中心页面添加签到按钮和相关方法
		// 在模板中添加签到按钮
		async dailySign() {
			if (this.isSigning) return;
			
			this.isSigning = true;
			try {
				const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
				if (!userInfo || !userInfo._id) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				const res = await uniCloud.callFunction({
					name: 'scoreManager',
					data: {
						action: 'daily_sign',
						userId: userInfo._id
					}
				});
				
				console.log('签到云函数返回结果:', res)
				
				if (res.result.code === 200) {
					const data = res.result.data;
					uni.showToast({ 
						title: `签到成功，获得${data.currentScore}积分`, 
						icon: 'success',
						duration: 2000
					});
					// 刷新积分显示
					this.getAllUserStats();
				} else {
					uni.showToast({ 
						title: res.result.msg, 
						icon: 'none' 
					});
				}
			} catch (error) {
				console.error('签到失败:', error);
				uni.showToast({ 
					title: '签到失败', 
					icon: 'error' 
				});
			} finally {
				this.isSigning = false;
			}
		},

		// 联系客服
		contactService() {
			uni.showActionSheet({
				itemList: ['在线客服', '电话客服'],
				success: (res) => {
					switch (res.tapIndex) {
						case 0:
							this.openOnlineService();
							break;
						case 1:
							this.callService();
							break;
						case 2:
							this.openFeedback();
							break;
						case 3:
							this.openFAQ();
							break;
					}
				}
			});
		},

		// 在线客服
		openOnlineService() {
			// 直接跳转到客服聊天页面，传递newChat参数表示开始新对话
			uni.navigateTo({
				url: '/pages/message/CustomerService/CustomerService?newChat=true',
				fail: (err) => {
					console.error('跳转客服页面失败:', err);
					uni.showToast({
						title: '客服系统暂时不可用',
						icon: 'none',
						duration: 2000
					});
				}
			});
		},

		// 电话客服
		callService() {
			uni.showModal({
				title: '电话客服',
				content: '客服热线：400-123-4567\n工作时间：9:00-18:00',
				confirmText: '拨打电话',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.makePhoneCall({
							phoneNumber: '400-123-4567',
							fail: () => {
								uni.showToast({
									title: '拨打失败',
									icon: 'none'
								});
							}
						});
					}
				}
			});
		},

		// 意见反馈
		openFeedback() {
			uni.showModal({
				title: '意见反馈',
				content: '您可以通过以下方式向我们反馈：\n\n• 邮箱：feedback@campus.com\n• QQ群：123456789\n• 微信群：扫码加入',
				showCancel: false,
				confirmText: '知道了'
			});
		},

		// 常见问题
		openFAQ() {
			uni.showActionSheet({
				itemList: ['如何发布任务？', '如何获得积分？', '账号安全问题', '支付相关问题'],
				success: (res) => {
					const faqContent = [
						'发布任务步骤：\n1. 点击首页"+"按钮\n2. 选择任务类型\n3. 填写任务详情\n4. 设置悬赏金额\n5. 发布任务',
						'获得积分方式：\n• 每日签到：+5积分\n• 完成任务：+10-50积分\n• 发布高质量内容：+20积分\n• 邀请好友：+100积分',
						'账号安全：\n• 设置强密码\n• 绑定手机号\n• 开启二步验证\n• 定期修改密码',
						'支付问题：\n• 支持微信、支付宝\n• 充值即时到账\n• 提现1-3个工作日\n• 如有问题请联系客服'
					];
					
					uni.showModal({
						title: '常见问题',
						content: faqContent[res.tapIndex],
						showCancel: false,
						confirmText: '知道了'
					});
				}
			});
		},
	},

	onShow() {
		this.checkLoginStatus();
		this.getUserInfo();
	},
}
</script>

<style>
	:root {
		--primary-color: #409EFF;
		--primary-color-light: #79bbff;
		--bg-color: #F5F7FA;
		--card-bg-color: #FFFFFF;
		--text-color-primary: #303133;
		--text-color-regular: #606266;
		--text-color-secondary: #909399;
		--border-color: #E4E7ED;
	}
	
	.cursor-pointer {
		cursor: pointer;
	}

	.user-page-container {
		position: relative;
		min-height: 100vh;
		background-color: var(--bg-color);
		overflow: hidden;
	}

	.page-background {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 450rpx;
		background: linear-gradient(to bottom, var(--primary-color), var(--primary-color-light));
		border-bottom-left-radius: 50rpx;
		border-bottom-right-radius: 50rpx;
	}

	.bg-image {
		position: absolute;
		bottom: 0;
		width: 100%;
		opacity: 0.1;
	}

	.header-section {
		padding: 40rpx 30rpx;
		position: relative;
		z-index: 1;
	}

	/* 登录状态样式 */
	.user-card {
		display: flex;
		align-items: center;
		padding: 20rpx;
	}

	.user-card-avatar .avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		border: 4rpx solid rgba(255, 255, 255, 0.5);
	}
	
	.user-card-info {
		flex: 1;
		margin-left: 30rpx;
		color: #000000;
	}

	.user-name-line {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.user-name {
		font-size: 20px;
		font-weight: 500;
	}

	.edit-icon {
		margin-left: 16rpx;
		opacity: 0.8;
	}
	
	.user-meta {
		font-size: 13px;
		opacity: 0.9;
		background: rgba(0, 0, 0, 0.1);
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		display: inline-block;
	}
	
	.user-score-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #000000;
		background: rgba(255, 255, 255, 0.15);
		border-radius: 20rpx;
		padding: 16rpx 24rpx;
	}
	
	.score-value {
		font-size: 18px;
		font-weight: 600;
	}
	
	.score-label {
		font-size: 12px;
		opacity: 0.9;
	}

	/* 未登录状态样式 */
	.not-login-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;
	}
	
	.default-avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		margin-bottom: 30rpx;
		background-color: #E9EEF3;
	}
	
	.login-btn {
		background: #FFFFFF;
		padding: 18rpx 80rpx;
		border-radius: 40rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
		transition: all 0.2s ease;
	}
	
	.login-btn text {
		color: var(--primary-color);
		font-size: 16px;
		font-weight: 500;
	}
	
	.login-btn:active {
		transform: scale(0.98);
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}
	
	.content-wrapper {
		position: relative;
		z-index: 2;
		padding: 0 30rpx;
		margin-top: -60rpx; /* 使卡片上移，部分覆盖背景 */
	}

	.card-section {
		background-color: var(--card-bg-color);
		border-radius: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.04);
		overflow: hidden;
	}
	
	/* 数据卡片 */
	.stats-group {
		position: relative;
	}
	
	.data-card {
		padding: 30rpx;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.card-title {
		font-size: 16px;
		font-weight: 600;
		color: var(--text-color-primary);
	}

	.data-grid {
		display: flex;
		flex-wrap: wrap;
		text-align: center;
	}

	.data-item {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx 0;
	}
	
	.data-card.data-grid {
		justify-content: space-between;
	}
	
	.data-card .data-item {
		width: auto;
		flex-grow: 1;
	}
	
	/* 活动中心有两个项目，让它们平分 */
	.card-section:last-child .data-item {
		width: 50%;
	}

	.data-value {
		font-size: 20px;
		font-weight: 600;
		color: var(--text-color-primary);
		margin-bottom: 8rpx;
	}

	.data-label {
		font-size: 12px;
		color: var(--text-color-secondary);
	}

	.login-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(255, 255, 255, 0.7);
		backdrop-filter: blur(6rpx);
		-webkit-backdrop-filter: blur(6rpx);
		z-index: 10;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 24rpx;
	}

	.mask-text {
		padding: 12rpx 24rpx;
		background-color: rgba(0, 0, 0, 0.05);
		border-radius: 100rpx;
		color: var(--text-color-regular);
		font-size: 14px;
	}

	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #FFFFFF;
		border-top: 1px solid #E4E7ED;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 25%;
	}

	.tab-item text {
		font-size: 12px;
		color: var(--text-color-secondary);
		margin-top: 4rpx;
	}

	.tab-item.active {
		color: var(--primary-color);
	}

	/* 新增功能导航区样式 */
	.nav-section {
		display: flex;
		justify-content: space-around;
		padding: 20rpx;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.nav-item text {
		font-size: 12px;
		color: var(--text-color-secondary);
		margin-top: 4rpx;
	}

	/* 在用户中心页面添加签到按钮和相关方法 */
	/* 在模板中添加签到按钮 */
	.sign-section {
		position: fixed;
		bottom: 100rpx; /* Adjust based on tab bar height */
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		z-index: 10;
		display: flex;
		justify-content: center;
	}

	.sign-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(90deg, #4080FF, #60A9FF);
		color: #fff;
		font-size: 16px;
		font-weight: 600;
		padding: 16rpx 30rpx;
		border-radius: 30rpx;
		box-shadow: 0 4px 12px rgba(64, 128, 255, 0.2);
		transition: all 0.2s ease;
	}

	.sign-btn:active {
		transform: scale(0.98);
		box-shadow: 0 2px 6px rgba(64, 128, 255, 0.1);
	}

	.sign-btn[disabled] {
		background: #ccc;
		color: #888;
		box-shadow: none;
		cursor: not-allowed;
	}

	/* 浮动客服按钮 */
	.floating-service-btn {
		position: fixed;
		top: 100rpx; /* 在签到按钮和底部导航栏之间 */
		right: 30rpx;
		width: 80rpx;
		height: 80rpx;
		background: linear-gradient(135deg, #67C23A, #85CE61);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 6rpx 20rpx rgba(103, 194, 58, 0.3);
		z-index: 1000;
		transition: all 0.3s ease;
		animation: pulse 2s infinite;
	}

	.floating-service-btn:active {
		transform: scale(0.9);
		box-shadow: 0 4rpx 15rpx rgba(103, 194, 58, 0.2);
	}

	/* 客服按钮脉冲动画 */
	@keyframes pulse {
		0% {
			box-shadow: 0 6rpx 20rpx rgba(103, 194, 58, 0.3), 0 0 0 0 rgba(103, 194, 58, 0.7);
		}
		50% {
			box-shadow: 0 6rpx 20rpx rgba(103, 194, 58, 0.3), 0 0 0 10rpx rgba(103, 194, 58, 0);
		}
		100% {
			box-shadow: 0 6rpx 20rpx rgba(103, 194, 58, 0.3), 0 0 0 0 rgba(103, 194, 58, 0);
		}
	}
</style>